<?php
/**
 * Created by PhpStorm.
 * User: henry
 * Date: 2017/2/23
 * Time: 下午2:07
 */

namespace business\base\services;

use business\base\models\QualificationLevelModel;
use yii\data\ActiveDataProvider;
use yii\db\Query;

class QualificationService
{
    /**
     * 获得资质等级实例
     * @param $queryParams
     * @return QualificationLevelModel
     */
    public function getQualificationLevel($queryParams)
    {
        $query = QualificationLevelModel::find();
        $query->andFilterWhere([
            "level_code" => $queryParams['level_code'],
        ]);
        $dataProvider = new ActiveDataProvider([
            "query" => $query,
            'pagination' => [
                'pageSize' => 1,
            ],
        ]);
        $result = $dataProvider->getModels();
        if (!empty($result) && sizeof($result) > 0) {
            return $result[0];
        }
        return null;
    }

    /**
     * @param $code
     * @return array|null|QualificationLevelModel
     */
    public function getQualificationLevelByCode($code)
    {
        return QualificationLevelModel::find()->where('level_code=:code', [':code' => $code])->one();
    }

    public function getQualificationLevelList($condition, $fields = '*'){
        return (new Query)
            ->from('b2b_parameter.bsp_qualification_level')
            ->select($fields)
            ->where($condition)
            ->createCommand(\Yii::$app->db)
            ->queryAll();
    }

    public function getQualificationByCondition($condition, $fields = '*'){
        return (new Query())
            ->from('b2b_parameter.bsp_qualification')
            ->select($fields)
            ->where($condition)
            ->createCommand(\Yii::$app->db)
            ->queryAll();
    }

    /**
     * 根据资质以及等级 显示对应名称
     * eg: qual1-level1,qual2-level2
     * @param $codes
     * @return mixed|null|string
     */
    public function  getQualificationNameByCodesV2($codes)
    {
        if (empty($codes)) {
            return null;
        }
        if(substr($codes, -1, 1) == ','){
            $codes = substr($codes, 0, -1);
        }

        $arrays = explode(',', $codes);
        $result = '';

        $condition = array(
            'qualification_code' => $arrays
        );
        $fields = 'qualification_name';
        $list = $this->getQualificationByCondition($condition, $fields);
        if($list){
            $result = implode(',', array_column($list, 'qualification_name'));
        }

        return $result;
    }
    
}